﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace BaseFunction
{
    public class StringHelp
    {
        /// <summary>
        /// 根据数字 1-9  返回对应汉字一~九
        /// </summary>
        /// <param name="Number">只能为一位数</param>
        /// <returns></returns>
        public static string GetWordNumber(int Number)
        {
            string[] s = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };
            if (Number > 10)
            {
                return "null";
            }
            else
            {
                return s[Number];
            }
        }

        /// <summary>
        /// 获取随机码
        /// </summary>
        /// <param name="CodeCount">随机码长度</param>
        /// <returns></returns>
        public static string RandomCode(int CodeCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9";
            string[] allCharArray = allChar.Split(',');
            string RandomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }

                int t = rand.Next(9);

                while (temp == t)
                {
                    t = rand.Next(9);
                }

                temp = t;
                RandomCode += allCharArray[t];
            }
            return RandomCode;
        }


        /// <summary>
        /// 根据当前日期 生成定订单号 [年月日时分秒毫秒]
        /// </summary>
        /// <returns></returns>
        public static string GetOrder()
        {
            string code = DateTime.Now.Year + "" + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
            return code.Replace("-", "").Replace("/", "").Replace(" ", "");
        }


        /// <summary>
        ///  验证是否为数字 并验证是否为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int IsNumberAndNotnull(string str, int DefaultVal)
        {
            if (string.IsNullOrEmpty(str))
            {
                return DefaultVal;
            }
            int TempInt = 0;
            if (int.TryParse(str, out TempInt))
            {
                if (TempInt > 0)
                {
                    return TempInt;
                }
                else
                {
                    return DefaultVal;
                }
            }
            else
            {
                return DefaultVal;
            }
        }

        /// <summary>
        /// 格式化逗号分隔的字符串   返回首尾没有逗号的符合SQL查询条件的字符串 (字符必须大于0)
        /// 例如 ,,1,,,2,3,,4,5,
        /// 返回:1,2,3,4,5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string formatStrByComma(string str)
        {
            if (str + "" == "")
            {
                return "";
            }
            string[] tempStr = str.Split(',');
            str = "";
            for (int i = 0; i < tempStr.Length; i++)
            {
                if (IsNumberAndNotnull(tempStr[i], 0) > 0)
                {
                    str += tempStr[i] + ",";
                }
            }
            if (str != "")
            {
                str = str.Remove(str.Length - 1);
            }
            return str;
        }

        /// <summary>
        /// 获取安全的字符串
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string GetSafeStr(string Str)
        {
            if (Str.Length > 0)
            {
                string SqlStr = "'|and|exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare|script";

                string[] anySqlStr = SqlStr.ToString().ToLower().Split('|');
                for (int i = 0; i < anySqlStr.Length; i++)
                {
                    Str = Str.Replace(anySqlStr[i], "");
                }
            }
            return Str;
        }

        /// <summary>
        /// 过滤String中的HTML标签
        /// </summary>
        /// <param name="strHtml">要过滤的html字符串</param>
        /// <returns></returns>
        public static string FilterHTML(string strHtml)
        {
            string[] aryReg ={
								 @"<script[^>]*?>.*?</script>",
								 @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
								 @"([\r\n])[\s]+",
								 @"&(quot|#34);",
								 @"&(amp|#38);",
								 @"&(lt|#60);",
								 @"&(gt|#62);",
								 @"&(nbsp|#160);",
								 @"&(iexcl|#161);",
								 @"&(cent|#162);",
								 @"&(pound|#163);",
								 @"&(copy|#169);",
								 @"&#(\d+);",
								 @"-->",
								 @"<!--.*\n"

							 };
            string[] aryRep = {
								  "",
								  "",
								  "",
								  "\"",
								  "&",
								  "<",
								  ">",
								  " ",
								  "\xa1",//chr(161),
								  "\xa2",//chr(162),
								  "\xa3",//chr(163),
								  "\xa9",//chr(169),
								  "",
								  "\r\n",
								  ""
							  };
            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }
            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");

            return strOutput;
        }

        #region 截取字符串的长度(重载1次)
        /// <summary>
        /// 截取字符串的长度
        /// </summary>
        /// <param name="Str">要截取的字符串</param>
        /// <param name="StrMaxLength">要截取的字符串的长度</param>
        /// <returns></returns>
        public static string CutStr(string Str, int StrMaxLength)
        {
            if (Str.Length > StrMaxLength)
            {
                Str = Str.Substring(0, StrMaxLength);
                Str += "...";
            }
            return Str;
        }

        /// <summary>
        /// 截取字符串的长度
        /// </summary>
        /// <param name="Str">要截取的字符串</param>
        /// <param name="StrMaxLength">要截取的字符串的长度</param>
        /// <param name="ReplaceStr">多余的长度要替换的字符</param>
        /// <returns></returns>
        public static string CutStr(string Str, int StrMaxLength, string ReplaceStr)
        {
            if (Str.Length > StrMaxLength)
            {
                Str = Str.Substring(0, StrMaxLength) + ReplaceStr;
            }
            return Str;
        }
        #endregion


        /// <summary>
        /// 返回文件的扩展名
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>返回.xxx</returns>
        public static string Extend(string fileName)
        {
            return "." + fileName.Substring(fileName.LastIndexOf("."));
        }


        /// <summary>
        /// 判断上传的文件是否合法
        /// </summary>
        /// <param name="AllowExtedList">允许的后缀名（包含.）</param>
        /// <param name="Extend">当前后缀名（包含.）</param>
        /// <returns></returns>
        public static bool AllowExtend(string[] AllowExtedList, string Extend)
        {
            foreach (string item in AllowExtedList)
            {
                if (item == Extend)
                {
                    return true;
                }
            }
            return false;
        }





        /// <summary>
        /// 查看以某某分割的字符串是否包含某个字符串<br/>
        /// 如:a,b,c,d,   是否包含  a  调用HasContains("a,b,c,d, ","a",',')
        /// </summary>
        /// <param name="srcStr">原始字符串</param>
        /// <param name="contain">被包含的字符串</param>
        /// <param name="split">以什么分割</param>
        /// <returns></returns>
        public static bool HasContains(string srcStr, string contain, char split)
        {
            List<string> lstr = new List<string>();
            foreach (string str in srcStr.Split(split))
            {
                lstr.Add(str);
            }
            return lstr.Contains(contain);
        }




        /// <summary>
        /// 查看以某某分割的字符串是否包含某个字符串<br/>
        /// 如:a,b,c,d,   是否包含  a  调用HasContains("a,b,c,d, ","a,b,c,d",',')
        /// </summary>
        /// <param name="srcStr">原始字符串</param>
        /// <param name="contain">被包含的字符串</param>
        /// <param name="split">以什么分割</param>
        /// <returns></returns>
        public static bool HasContainsArray(string srcStr, string contain, char splitsrcStr, char splitcontain)
        {
            List<string> lstr1 = new List<string>();
            bool flag = false;
            foreach (string str in srcStr.Split(splitsrcStr))
            {
                lstr1.Add(str);
            }
            foreach (string str in contain.Split(splitcontain))
            {
                if (lstr1.Contains(str))
                {
                    flag = true;
                }
            }
            return flag;
        }

        /// <summary>
        /// 时差,如几分钟前...
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DateStringFromNow(DateTime dt, string formate)
        {
            TimeSpan span = DateTime.Now - dt;
            if (span.TotalDays > 60)
            {
                return dt.ToString(formate);
            }
            else
                if (span.TotalDays > 30)
                {
                    return
                    "1个月前";
                }
                else
                    if (span.TotalDays > 14)
                    {
                        return
                        "2周前";
                    }
                    else
                        if (span.TotalDays > 7)
                        {
                            return
                            "1周前";
                        }
                        else
                            if (span.TotalDays > 1)
                            {
                                return
                                string.Format("{0}天前", (int)Math.Floor(span.TotalDays));
                            }
                            else
                                if (span.TotalHours > 1)
                                {
                                    return
                                    string.Format("{0}小时前", (int)Math.Floor(span.TotalHours));
                                }
                                else
                                    if (span.TotalMinutes > 1)
                                    {
                                        return
                                        string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
                                    }
                                    else
                                        if (span.TotalSeconds >= 1)
                                        {
                                            return
                                            string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));
                                        }
                                        else
                                        {
                                            return
                                            "1秒前";
                                        }
        }




        /// <summary>
        /// 从字符串中移除 指定的字符  并移除该字符后面的分隔符
        /// </summary>
        /// <param name="srcStr">原始字符串</param>
        /// <param name="contain">被包含的字符串</param>
        /// <param name="split">以什么分割</param>
        /// <returns></returns>
        public static string RemoveChar(string srcStr, string contain, char split)
        {
            List<string> lstr = new List<string>();
            foreach (string str in srcStr.Split(split))
            {
                if (str != contain)
                    lstr.Add(str);
            }
            string tempStr = "";
            for (int i = 0; i < lstr.Count; i++)
            {
                if (lstr[i] == "")
                    continue;
                tempStr += lstr[i] + split;
            }
            return tempStr;
        }






        /// <summary>
        /// 以汉字形式返回今天是星期几
        /// </summary>
        /// <returns></returns>
        public static string GetWeek()
        {
            DayOfWeek dayOfWeek = DateTime.Now.DayOfWeek;
            string week = "";
            switch (dayOfWeek)
            {
                case DayOfWeek.Monday:
                    week = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    week = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    week = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    week = "星期四";
                    break;
                case DayOfWeek.Friday:
                    week = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    week = "星期六";
                    break;
                case DayOfWeek.Sunday:
                    week = "星期日";
                    break;
            }
            return week;
        }

        /// <summary>
        /// 高亮关键字
        /// </summary>
        /// <param name="input">输入的字符串</param>
        /// <param name="keyword">需要高亮的关键字</param>
        /// <param name="color">高亮的颜色  默认值:#ff0000</param>
        /// <returns></returns>
        public static string HighLightKeyWord(string input, string keyword, string color)
        {
            if (keyword.Trim() != "")
            {
                color = color == "" ? "#ff0000" : color;
                string input2 = input.ToUpper();
                string keyword2 = keyword.ToUpper();
                int l = 0;
                while (true)
                {
                    int input2IndexOf = input2.IndexOf(keyword2);
                    if (input2IndexOf <= -1)
                        break;
                    input = input.Insert(input2IndexOf + l, "<font color='" + color + "'>").Insert(input2IndexOf + keyword2.Length + 15 + color.Length + l, "</font>");
                    input2 = input2.Remove(input2IndexOf, keyword2.Length);
                    l = keyword2.Length + l + 22 + color.Length;
                }
            }
            return input;
        }

        /// <summary>
        /// 格式化list到字符串并用分隔符隔开
        /// </summary>
        /// <param name="list">list列表</param>
        /// <param name="splitstring">自定义分割字符</param>
        /// <param name="add">是否加上引号</param>
        /// <returns></returns>
        public static string ConvertListToString(List<string> list,string splitstring,bool add)
        {
            string result="";
            for (int i = 0; i < list.Count; i++)
            {
                if (add)
                {
                    result += "'"+list[i]+"'";
                }
                else
                {
                    result += list[i];
                }
                if (i != list.Count - 1)
                {
                    result += splitstring;
                }
            }
            return result;
        }

    }
}
